package io.arukas.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * Created by IntelliJ IDEA. <br/>
 *
 * @author 牛玉贤 <br/>
 * @date 08/05/2020 16:15 <br/>
 * @email ncc0706@gmail.com <br/>
 */
public class HttpBasicAuthorize implements Filter {

    private static String username = "test";
    private static String password = "test";

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        String authorization = httpServletRequest.getHeader("Authorization");
        logger.info("authorization: {}", authorization);
        if (ObjectUtils.isEmpty(authorization) || authorization.length() <= 6) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
//            httpResponse.setCharacterEncoding("UTF-8");
//            httpResponse.setContentType("application/json; charset=utf-8");
            httpResponse.setHeader("WWW-Authenticate", "Basic realm=hello");
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

//            ObjectMapper mapper = new ObjectMapper();
//            Map<String, Object> resultMsg = new HashMap<>();
//            resultMsg.put("message", "请输入用户名密码");
//            httpResponse.getWriter().write(mapper.writeValueAsString(resultMsg));
            return;
        } else {
            chain.doFilter(request, response);
        }
    }

}
